package com.sou.technologytool.api;

import android.content.Context;
import android.content.Intent;
import android.util.Log;


import com.benben.commoncore.utils.StringUtils;
import com.sou.technologytool.BuildConfig;
import com.sou.technologytool.ui.login.LoginActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Api {
    private static OkHttpClient client;
    private static String requestUrl;
    private static HashMap<String, Object> mParams;
    private static Boolean mToken;
    public static Api api = new Api();

    public Api() {

    }

    public static Api config(String url, HashMap<String, Object> params) {
        client = new OkHttpClient.Builder()
                .build();
        if(BuildConfig.DEBUG){
            if (Config.IS_URL){
                requestUrl = ApiConfig.BASE_URL + url;
            }else {
                requestUrl = ApiConfig.TEST_BASE_URL + url;
            }
        }else {
            requestUrl = ApiConfig.BASE_URL + url;
        }
        mParams = params;
        mToken = false;
        return api;
    }

    public static Api config(String url, HashMap<String, Object> params, Boolean hasToken) {
        client = new OkHttpClient.Builder()
                .build();
        if(BuildConfig.DEBUG){
            if (Config.IS_URL){
                requestUrl = ApiConfig.BASE_URL + url;
            }else {
                requestUrl = ApiConfig.TEST_BASE_URL + url;
            }
        }else {
            requestUrl = ApiConfig.BASE_URL + url;
        }
        mParams = params;
        mToken = hasToken;
        return api;
    }

    public void formUpload(Context context, final TtitCallback callback) {
        String filePath = "";
        if (mParams.containsKey("file")) {
            filePath = mParams.get("file").toString();
        }
        File file = new File(filePath);
        RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
        requestBody.addFormDataPart("file", file.getName(), fileBody);
        for (Iterator<String> iter = mParams.keySet().iterator(); iter.hasNext(); ) {
            String key = iter.next();
            if (!key.equals("file")) {
                requestBody.addFormDataPart(key, mParams.get(key).toString());
            }
        }
        Request.Builder builder = new Request.Builder();
        builder.url(requestUrl).post(requestBody.build());
        builder.addHeader("Authorization", "Basic c2FiZXI6c2FiZXJfc2VjcmV0");
        if (mToken == true) {
            builder.addHeader("User-Type", "APP");
        }
        Request request = builder.build();
        final Call call = client.newCall(request);
        //第五步发起请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("onFailure", e.getMessage());
                callback.onFailure(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String result = response.body().string();
                callback.onSuccess(result);
            }
        });
    }

    public void formRequest(Context context, final TtitCallback callback) {
        FormBody.Builder builder = new FormBody.Builder();
        for (String key : mParams.keySet()) {
            builder.add(key, mParams.get(key).toString());
        }
        FormBody formBody = builder.build();
        Request.Builder requestBuilder = new Request.Builder()
                .url(requestUrl);
        requestBuilder = requestBuilder.addHeader("Authorization", "Basic c2FiZXI6c2FiZXJfc2VjcmV0");
        if (mToken == true) {
            requestBuilder = requestBuilder.addHeader("User-Type", "APP");
        }
//        Log.i("Unnamed-iiiii","formBody:"+formBody.toString());
        Request request = requestBuilder.post(formBody)
                .build();
        final Call call = client.newCall(request);
        //第五步发起请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("onFailure", e.getMessage());
                callback.onFailure(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String result = response.body().string();
                callback.onSuccess(result);
            }
        });
    }

    public void postRequest(Context context, final TtitCallback callback) {
//        Log.i("Unnamed-iiiii","mParams:"+mParams);
        JSONObject jsonObject = new JSONObject(mParams);
        String jsonStr = jsonObject.toString();
//        Log.i("Unnamed-iiiii","jsonStr:"+jsonStr);
        RequestBody requestBodyJson =
                RequestBody.create(MediaType.parse("application/json;charset=utf-8")
                        , jsonStr);
        Request.Builder requestBuilder = new Request.Builder();
        requestBuilder = requestBuilder.url(requestUrl);
        requestBuilder = requestBuilder.addHeader("Authorization", "Basic c2FiZXI6c2FiZXJfc2VjcmV0");
        requestBuilder = requestBuilder.addHeader("Content-Type", "application/json");
        if (mToken) {
            requestBuilder = requestBuilder.addHeader("User-Type", "APP");
        }
        Request request = requestBuilder
                .post(requestBodyJson)
                .build();
        //第四步创建call回调对象
        final Call call = client.newCall(request);
        //第五步发起请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("onFailure", e.getMessage());
                callback.onFailure(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String result = response.body().string();
                callback.onSuccess(result);
            }
        });
    }

    public void getRequest(Context context, final TtitCallback callback) {
        String url = getAppendUrl(requestUrl, mParams);
        Request.Builder requestBuilder = new Request.Builder();
        Log.e("onSuccess", url);
        requestBuilder = requestBuilder.url(url);
        requestBuilder = requestBuilder.addHeader("Authorization", "Basic c2FiZXI6c2FiZXJfc2VjcmV0");
        if (mToken == true) {
            requestBuilder = requestBuilder.addHeader("User-Type", "APP");
        }

        Request request = requestBuilder.get()
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("onFailure", e.getMessage());
                callback.onFailure(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String result = response.body().string();
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String code = jsonObject.getString("code");
                    if (code.equals("401")) {
                        Intent in = new Intent(context, LoginActivity.class);
                        context.startActivity(in);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                callback.onSuccess(result);
            }
        });
    }

    private String getAppendUrl(String url, Map<String, Object> map) {
        if (map != null && !map.isEmpty()) {
            StringBuffer buffer = new StringBuffer();
            Iterator<Entry<String, Object>> iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<String, Object> entry = iterator.next();
                if (StringUtils.isEmpty(buffer.toString())) {
                    buffer.append("?");
                } else {
                    buffer.append("&");
                }
                buffer.append(entry.getKey()).append("=").append(entry.getValue());
            }
            url += buffer.toString();
        }
        return url;
    }
}

